<template>
  <div :class="{ fullscreen: fullscreen }" class="tinymce-container" :style="{ width: containerWidth }">
    <textarea :id="tinymceId" class="tinymce-textarea" />
  </div>
</template>

<script>
/**
 * docs:
 * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
 */
import editorImage from './components/EditorImage'
import plugins from './plugins'
import toolbar from './toolbar'
import load from './dynamicLoadScript'
import { tinymceCDN } from 'tinymce'
import { getToken } from '@tapui/utils/auth'
import jquery from '@jQuery'
import { getBase64Image, base64ImgtoFile, readFileSizeUnit, bufferToBase64 } from '@/utils/mcrUtils'
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import axios from '@tapui/utils/request'
// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
// const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'
export default {
  name: 'Tinymce',
  components: { editorImage },
  props: {
    id: {
      type: String,
      default: function() {
        return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    value: {
      type: String,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    placeholder: {
      type: String,
      default: '请输入内容'
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table'
    },
    height: {
      type: [Number, String],
      required: false,
      default: 360
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto'
    },
    extrtaParam: {}
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      extraParam: {},
      readOnly: false,
      languageTypeList: {
        zh: 'zh_CN'
      }
    }
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() => window.tinymce.get(this.tinymceId).setContent(val || ''))
      }
    }
  },
  mounted() {
    this.init()
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce()
    }
  },
  deactivated() {
    this.destroyTinymce()
  },
  destroyed() {
    this.destroyTinymce()
  },
  methods: {
    init() {
      // dynamic load tinymce from cdn
      load(tinymceCDN, (err) => {
        if (err) {
          this.$message.error(err.message)
          return
        }
        this.initTinymce()
      })
    },
    initTinymce() {
      const _this = this
      const readOnly = _this.readonly
      window.tinymce.init({
        selector: `#${this.tinymceId}`,
        base_url: '/static/plugins/tinymce',
        language: 'zh_CN',
        plugins: 'print preview uploadimage paste wordcount ax_wordlimit image table powerpaste',
        toolbar: 'undo redo | styleselect | fontselect | fontsizeselect | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | charmap bullist numlist outdent indent | table image',
        height: 650, // 编辑器高度
        min_height: 400,
        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
        font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
        images_size_limt: '2MB',
        images_upload_base_path: process.env.BASE_API,
        extrta_param: _this.extrtaParam,
        // ax_wordlimit_num: 2000,
        placeholder: _this.placeholder,
        readonly: readOnly,
        convert_urls: false,
        ax_wordlimit_callback: function(editor, txt, num) {
          _this.$alert('当前字数：' + txt.length + '，限制字数：' + num)
        },
        autosave_ask_before_unload: false,
        code_dialog_height: 450,
        code_dialog_width: 1000,
        menubar: this.menubar,
        branding: false,
        init_instance_callback: (editor) => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          })
        },
        images_upload_handler: function(blobInfo, success, failure) {
          let formdata = new FormData()
          let file = blobInfo.blob()
          var fileSize = file.size
          if (Number(fileSize) > (2 * 1024 * 1024)) {
            failure('图片大小限制2M以内!')
            return
          }
          formdata.append("file", file, file.name)
          formdata.append("sourceId", _this.extrtaParam.sourceId)
          formdata.append("sourceType", _this.extrtaParam.sourceType)
          postAction("/cms/guidelineLog/uploadForTinymceEditor", formdata).then((res) => {
            var url = res.data[0]
            success(process.env.BASE_API + url)
          }).catch((err) => {
            failure(err.msg)
          })
        }
      })
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }
      if (tinymce) {
        tinymce.destroy()
      }
    },
    setReadonly() {
      window.tinymce.editors[this.tinymceId].setMode('readonly') // 开启只读模式
    },
    setEditor() {
      window.tinymce.editors[this.tinymceId].setMode('design') // 开启编辑模式
    },
    setContent(value) {
      if (value) {
        window.tinymce.get(this.tinymceId).setContent(value)
      } else {
        window.tinymce.get(this.tinymceId).setContent("")
      }
    },
    getContent() {
      return window.tinymce.get(this.tinymceId).getContent()
    }
  }
}
</script>

<style lang="scss" scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}

.tinymce-container {
  /deep/ {
    .mce-fullscreen {
      z-index: 10000;
    }
  }
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}

.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  z-index: 2005;
}

.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}

.editor-upload-btn {
  display: inline-block;
}
</style>
